package com.sumainfor.pc.cfo.service.impl;

import com.sumainfor.common.exception.TCException;
import com.sumainfor.common.util.CustomMap;
import com.sumainfor.common.util.JsonResult;
import com.sumainfor.common.util.ObjectUtil;
import com.sumainfor.common.utlis.ParamsCommon;
import com.sumainfor.pc.cfo.dao.BalanceLogMapper;
import com.sumainfor.pc.cfo.dao.BalanceMapper;
import com.sumainfor.pc.cfo.service.SettleProductService;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Map;

/**
 * @Author PuaChen
 * @Create 2018-12-14 11:21
 * 结算单操作服务
 */
@Service
@Log4j2
@Transactional(rollbackFor = Exception.class)
public class SettleProductServiceImpl implements SettleProductService {

    @Autowired
    private BalanceLogMapper balanceLogMapper;

    @Autowired
    private BalanceMapper balanceMapper;

    /**
     * 修改供应商的欠款金额
     *
     * @param supId
     * @param price
     * @return
     */
    @Override
    public JsonResult updateBalanceBySup(String supId, BigDecimal price) {
        log.info("供应商编号:{} - 款:{} ", supId, price);
        Map<String, Object> map = balanceMapper.getBalanceOne(supId);
        if (MapUtils.isEmpty(map)) {
            //新增的操作
            int row = balanceMapper.insertBalance(ParamsCommon.commonInsertParms(CustomMap.create()
                            .put("SupId", supId)
                            .put("PaymentDays", price)
                    , getClass()));
            if (row <= 0) {
                return JsonResult.error("操作失败");
            }
        } else {
            //更新的操作
            //计算总价
            BigDecimal sum = ObjectUtil.convertBigDecimal(map.get("PaymentDays"));
            int row = balanceMapper.updateBalance(ParamsCommon.commonUpdateParms(CustomMap.create()
                            .put("SupId", supId)
                            .put("PaymentDays", sum.add(price))
                    , getClass()));
            if (row <= 0) {
                return JsonResult.error("更新失败");
            }
        }
        //记录日志
        int row = balanceLogMapper.insertBalance(ParamsCommon.commonUpdateParms(CustomMap.create()
                        .put("SupId", supId)
                        .put("PaymentDays", price)
                , getClass()));
        if (row <= 0) {
            throw new TCException("记录日志失败");
        }
        return JsonResult.success();
    }

}
